from io import BytesIO

from django import forms
from django.http import HttpResponse

from django.shortcuts import render, redirect
from django.urls import reverse

from wepapi.models import Admin
from wepapi.utils.bootstrap import Bootstrap, BootStrapForm
from wepapi.utils.code import check_code
from wepapi.utils.encrypt import md5


class AccountForm(BootStrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True),
        required=True
    )

    code = forms.CharField(
        label="图片验证码",
        widget=forms.TextInput,
        required=True
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)
        # return '202cb962ac59075b964b07152d234b70'


class AccountModelForm(Bootstrap):
    class Meta:
        model = Admin
        fields = ["username", "password"]


    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)

def account_login(request):
    """登录"""
    if request.method == "GET":
        form = AccountForm()
        return render(request, 'account_login.html', {'form': form})

    uform = AccountForm(data=request.POST)
    if uform.is_valid():
        # 去数据库校验用户名和密码是否正确,获取用户对象，None
        # admin_object = Admin.objects.filter(username=uform.cleaned_data["username"], password=uform..cleaned_data["password"]).first()
        user_code = uform.cleaned_data.pop('code')
        img_code= request.session.get('img_code','')
        if img_code.upper()!=user_code.upper():
            uform.add_error("code", "验证码错误")
            return render(request, 'account_login.html', {'form': uform})

        admin_object = Admin.objects.filter(**uform.cleaned_data).first()

        if not admin_object:
            uform.add_error("password", "用户名和密码错误.")
            return render(request, 'account_login.html', {'form': uform})

        # 用户名和密码正确
        # 网站生成随机字符串，写到用户浏览器的cookie中；在写入到session中
        # request.session['info'] = uform.cleaned_data.get("username")
        request.session['info'] = {'id': admin_object.id, 'username': admin_object.username}
        # session 保存七天
        request.session.set_expiry(60*60*24*7)
        return redirect(reverse("admin_list"))

    return render(request, 'account_login.html', {'form': uform})


def account_logout(request):
    """注销"""
    request.session.clear()
    return redirect(reverse('account_login'))


def account_img(request):
    """生成图形验证码"""
    # 调用check_code 函数，生成图片
    img, code_string = check_code()
    # print(code_string)
    # 写入到自己的session 中(以便于后续后驱验证码在进行操作)
    request.session['img_code'] = code_string
    # 给session 设置60s超时
    request.session.set_expiry(60)
    stream = BytesIO()
    img.save(stream, 'PNG')
    return HttpResponse(stream.getvalue(), content_type='image/png')
